import json
from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql
from pymysql.cursors import DictCursor
import traceback

app = Flask(__name__)
CORS(app)

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'lqb',
    'charset': 'utf8mb4',
    'cursorclass': DictCursor
}


@app.route('/verify', methods=['POST'])
def verify_user():
    try:
        # 获取前端数据
        data = request.get_json()
        print(f"接收到登录请求: {data}")

        # 验证数据格式
        if not isinstance(data, dict):
            raise ValueError("数据格式应为 JSON 对象")
        if 'Name' not in data or 'Password' not in data:
            raise ValueError("数据必须包含 Name 和 Password 字段")

        # 提取参数
        userType = data['UserType']
        name = data['Name']
        password = data['Password']
        print(f"验证用户: {name}，密码长度: {len(password)}")
        student_is_exists = False
        admin_is_exists = False
        # 调用验证函数
        if(userType=="student"):
            student_is_exists = verify_student_in_database(name, password)
        else:
            admin_is_exists = verify_admin_in_database(name, password)

        if student_is_exists or admin_is_exists:
            return jsonify({
                "status": "success",
                "message": f"用户 {name} 登录成功",
                "data": {"username": name}  # 注意：这里返回username字段，与前端保持一致
            }), 200
        else:
            return jsonify({
                "status": "failed",
                "message": "账号或密码错误"
            }), 404
    except Exception as e:
        error_info = traceback.format_exc()
        print(f"登录验证失败: {str(e)}")
        print(f"错误堆栈:\n{error_info}")
        return jsonify({
            "status": "error",
            "message": f"服务器内部错误: {str(e)}"
        }), 500


def verify_student_in_database(name, password):
    """验证数据库中是否存在指定姓名和密码的记录"""
    try:
        print(f"尝试连接数据库: {DB_CONFIG['host']}/{DB_CONFIG['database']}")
        with pymysql.connect(**DB_CONFIG) as connection:
            with connection.cursor() as cursor:
                # 使用参数化查询防止SQL注入-+
                sql = "SELECT 1 FROM Face WHERE Name = %s AND Password = %s LIMIT 1"
                cursor.execute(sql, (name, password))
                result = cursor.fetchone()
                return result is not None
    except pymysql.Error as e:
        print(f"数据库查询失败: {e}")
        raise
    except Exception as e:
        print(f"验证过程出错: {e}")
        raise

def verify_admin_in_database(name, password):
    """验证数据库中是否存在指定姓名和密码的记录"""
    try:
        print(f"尝试连接数据库: {DB_CONFIG['host']}/{DB_CONFIG['database']}")
        with pymysql.connect(**DB_CONFIG) as connection:
            with connection.cursor() as cursor:
                # 使用参数化查询防止SQL注入-+
                sql = "SELECT 1 FROM Admin WHERE Name = %s AND Password = %s LIMIT 1"
                cursor.execute(sql, (name, password))
                result = cursor.fetchone()
                return result is not None
    except pymysql.Error as e:
        print(f"数据库查询失败: {e}")
        raise
    except Exception as e:
        print(f"验证过程出错: {e}")
        raise

if __name__ == '__main__':
    app.run(debug=True, port=5001)